package juc.imooccache;

import juc.imooccache.computable.Computable;
import juc.imooccache.computable.ExpensiveFunction;

import java.util.HashMap;

/**
 * @author fangbin
 * @desc  装饰器模式的应用。当使用synchronized修饰方法时，此时读取也会被阻塞
 * @date 2020/7/1 21:33
 */
public class ImoocCache2<A,V> implements Computable<A,V>{

    private final  HashMap<A,V> cache = new HashMap();
    private Computable<A,V> c;

    public ImoocCache2(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public synchronized  V compute(A arg) throws Exception {
        System.out.println("进入缓存机制");
        V result = cache.get(arg);
        if(result==null){
            result = c.compute(arg);
            cache.put(arg,result);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        ImoocCache2<String, Integer> stringIntegerImoocCache2 = new ImoocCache2<>(new ExpensiveFunction());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果:"+result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("667");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第二次计算结果:"+result);
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666");     //他不能立即获取到
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第三次计算结果:"+result);
            }
        }).start();


    }
}
